package com.chinamsp.codegen.convert.db.biz;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.chinamsp.codegen.config.CodeGenConfiguration;
import com.chinamsp.codegen.convert.db.dao.TableColumnDao;
import com.chinamsp.codegen.convert.db.model.TableColumn;
import com.chinamsp.dydb.crud.BaseBiz;
import com.chinamsp.dydb.query.ConditionBuilder;
import com.chinamsp.dydb.query.FieldType;
import com.chinamsp.dydb.query.OrderByBuilder;
import com.chinamsp.dydb.query.SymbolType;

/**
 * 走起
 * @author shifenghu
 *
 */
@Service
@ConditionalOnBean(CodeGenConfiguration.class)
public class TableColumnBiz extends BaseBiz<TableColumn, TableColumnDao> {
	
	
	/**
	 * 查询特定条件的table 字段信息
	 * @param tableSchema
	 * @param includes
	 * @param exclusions
	 * @return
	 */
	public Map<String, List<TableColumn>> findBySchema(String tableSchema, List<String> includes, List<String> exclusions){
		Assert.notNull(tableSchema, "要查询的库不能为空");
		ConditionBuilder builder = ConditionBuilder.newDefault();
		builder.add("tableSchema", tableSchema);
		if (CollectionUtils.isNotEmpty(includes)) {
			builder.add("tableName",FieldType.STRING, SymbolType.IN, includes);
		}
		else if (CollectionUtils.isNotEmpty(exclusions)) {
			builder.add("tableName",FieldType.STRING, SymbolType.NOT_IN, includes);
		}
		// 查询符合条件的数据
		List<TableColumn> columns = find(null, builder.builds(), OrderByBuilder.newDefault().addAsc("tableName").builds());
		Map<String, List<TableColumn>> rs = new HashMap<>(64);
		List<TableColumn> list = null;
		for (TableColumn tc : columns) {
			// 如果未添加，则初始化并添加
			if (!rs.containsKey(tc.getTableName())) {
				list = new ArrayList<>(32);
				rs.put(tc.getTableName(), list);
			}
			list.add(tc);
		}
		
		return rs;
	}
	
	
}
